#!/usr/bin/perl
#
# Patch f_ctime based on "recdate" field from transactions in .txt file
#
use FileTable;
use HTTP::Date;
use Fcntl;

$DEBUG = 0;

$filename = shift;
$reccount = shift;
$reccount = 10000000 if !$reccount; # infinite...

if (! -f "$filename.conf") {
    $filename = $ENV{"COUNTER_ROOT"} . "/db/" . $filename;
}

$file = FileTable::open($filename, O_RDWR);
open(FILE, "$filename.txt") || die "Unable to open .txt file\n";
while (<FILE>) {
    chop;
    if (/^\/\/(\d+)/) {
	process();
	++ $recs;
	last if $recs > $reccount;
	undef $recdate;
	$key = $1;
    } elsif (/^recdate:/) {
	$recdate = $';
    }
}
for $act (keys(%act)) {
    print $act{$act}, " ", $act, "\n";
}

sub process {

    if ($recdate && $key ) {
	$rec = $file->get($key);
	if (!$rec) {
	    ++ $act{recnotindb};
	} elsif ($recdate ne $rec->{recdate}) {
	    $timestamp = str2time($recdate);
	    $nowstamp = str2time($rec->{f_ctime});
	    # Patch for timezone not handled by HTTP::Date
	    if (!defined($timestamp) && $recdate =~ /MET DST/) {
		$recdate =~ s/MET DST/MEST/;
		$timestamp = str2time($recdate);
	    }
	    if ($nowstamp < $timestamp) {
		print $rec->key(), ":", "Skip forwarddate from ",
	      HTTP::Date::time2iso($nowstamp), " to ", HTTP::Date::time2iso($timestamp), "\n" if $DEBUG;
		++ $act{skipforward};
	    } elsif ($nowstamp == $timestamp) {
		++ $act{samedate};
	    } elsif (defined($timestamp)) {
		if ($rec->{f_ctime}) {
		    $rec->{f_mtime} = $rec->{f_ctime};
		}
		$rec->{f_ctime} = HTTP::Date::time2iso($timestamp);
		print $rec->key(), ":", "Changed ctime from $$rec{f_mtime} to $$rec{f_ctime}\n" if $DEBUG;
		# Extremely dirty trick: Bypass the timestamping
		bless $rec, FileTable::Record;
		$rec->store("NOTEXT");
		++ $act{changed};
	    } else {
		print $rec->key(), ":";
		print "Unparseable recdate: $$rec{recdate}\n";
		++ $act{unparsed};
	    }
	} else {
	    my $newiso;
            my $timestamp = str2time($recdate);
	    if (!defined($timestamp) && $recdate =~ /MET DST/) {
		$recdate =~ s/MET DST/MEST/;
		$timestamp = str2time($recdate);
	    }
	    $newiso = HTTP::Date::time2iso($timestamp);
	    if ($newiso ne $rec->{f_ctime}) {
		if ($rec->{f_ctime} eq $rec->{f_mtime}) {
		    $rec->{f_mtime} = $newiso;
		}
		$rec->{f_ctime} = $newiso;
		$rec->store("NOTEXT");
		++ $act{changedtorec};
	    } else {
		++ $act{thesame};
	    }
	}
    } elsif ($key) {
	++ $act{datemissinginfile};
    }
}
